package com.gdut.simple.presenter;

import com.gdut.simple.R;
import com.gdut.simple.basic.BasicApplication;
import com.gdut.simple.common.LogUtils;
import com.gdut.simple.common.NetworkUtils;
import com.gdut.simple.common.RequestCallback;
import com.gdut.simple.contract.SquareContract;
import com.gdut.simple.data.entity.Post;
import com.gdut.simple.model.ISquareModel;
import com.gdut.simple.model.impl.SquareModelImpl;

import java.util.List;

public class SquarePresenter implements SquareContract.Presenter {

    private SquareContract.View mSquareView;
    private ISquareModel mSquareModel;

    public SquarePresenter(SquareContract.View view) {
        this.mSquareView = view;
        mSquareModel = new SquareModelImpl();
        mSquareView.setPresenter(this);
    }

    @Override
    public void refresh() {
        if (!NetworkUtils.isConnected(BasicApplication.getApplication())) {
            mSquareView.hideRefreshProgress();
            mSquareView.showMessage(BasicApplication.getApplication().getResources().getString(R.string.msg_error_net));
            return;
        }
        mSquareView.showRefreshProgress();
        mSquareModel.refresh(10, new RequestCallback<List<Post>>() {
            @Override
            public void onSuccess(List<Post> posts) {
                LogUtils.e("onSuccess:\n" + posts.toString() + "\n---end---");
                mSquareView.hideRefreshProgress();
                mSquareView.getItemList().clear();
                mSquareView.getItemList().addAll(posts);
                mSquareView.refreshList();
                LogUtils.e("onSuccess:\n" + mSquareView.getItemList().toString() + "\n===end===");
            }

            @Override
            public void onFailure(String message) {
                mSquareView.hideRefreshProgress();
                mSquareView.showMessage(BasicApplication.getApplication().getResources().getString(R.string.msg_refresh_fail));
            }
        });
    }

    @Override
    public void loadMore(int page) {
        if (!NetworkUtils.isConnected(BasicApplication.getApplication())) {
            mSquareView.showMessage(BasicApplication.getApplication().getResources().getString(R.string.msg_error_net));
            return;
        }
        mSquareModel.loadMore(page, 10, new RequestCallback<List<Post>>() {

            @Override
            public void onSuccess(List<Post> posts) {
                if (posts == null || posts.size() == 0) {
                    return;
                }
                mSquareView.getItemList().addAll(posts);
                mSquareView.refreshList();
            }

            @Override
            public void onFailure(String message) {
                mSquareView.showMessage(message);
            }
        });
    }

}
